


export class WSSHelper {
    static logCallback = (str: string) => { };

    recvCallback = (data: any) => { };
    socket: WebSocket;
    isOpen: boolean = false;
    time: number
    constructor() {
        this.time = setInterval(() => {
            this.send({ "cmd": "pong" })
        }, 5000)
    }
    start(url: string) {
        this.socket = new WebSocket(url);
        this.socket.onmessage = (ev) => {
            this.recive(ev);
        };
        this.socket.onopen = () => this.onOpen();
        this.socket.onclose = () => this.onClose();
        this.socket.onerror = (ev) => this.onError(ev);

    }
    send(data: any) {
        if (this.isOpen) {
            if (typeof data == "string") {
                this.socket.send(data);
            }
            else {
                this.socket.send(JSON.stringify(data));
            }

        }
    }
    enable(isStart: boolean, url: string) {
        if (url) {
            this.log("控制短视频弹幕" + "(" + (isStart ? "开启" : "关闭") + ")：" + url)
            this.send({ cmd: isStart ? "start" : "stop", url: url });
            return;
        }
        else {
            this.log("未设置短视频连接")
        }

    }
    stop() {
        if (this.isOpen) {
            this.socket.close();
        }
    }

    private log(str: string) {
        if (WSSHelper.logCallback) {
            WSSHelper.logCallback(str);
        }
    }
    private auth() {
        this.log("发起授权!")
        this.send({
            "cmd": "auth",//执行授权功能​
            "code": "999999" //授权码，卡密​
        })

    }
    private onOpen() {
        this.isOpen = true;
        this.log("启动websocket成功！")
        this.auth();
    }
    private onClose() {
        this.isOpen = false;
        this.log("关闭websocket！")
    }
    private onError(ev: Event) {
        this.log("websocket 异常:" + ev)
    }


    private recive(ev) {

        if (ev.data) {
            console.log("接收弹幕数据！", ev.data);
            if (typeof ev.data == "string") {
                if (ev.data.indexOf("{") > -1) {
                    var jdata = JSON.parse(ev.data);
                    this.log(`用户：(${jdata.name}),${jdata.msg}`);
                    this.recvCallback(jdata);
                } else {
                    this.log(`系统消息：(${ev.data}`);
                }

            }

        }
    }

}

